package com.rocksea.app.weight;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.rocksea.app.R;
import com.rocksea.app.db.SonicWave.SonicWave;
import com.rocksea.app.utils.PerUtils;
import com.rocksea.app.utils.UiUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author Administrator
 * @date 2017/11/23
 * 声波波列图
 *
 */

public class SonicWaveView extends RecyclerView
{

    public static final byte PATTERN_NORMAL = 0;//正常模式
    public static final byte PATTERN_EDIT = 1;//编辑模式
    private byte current_pattern = PATTERN_NORMAL;//当前模式  默认为正常
    private OnItemValidChangedListener onItemValidChangedListener;

    private SonicWaveAdpter sonicWaveAdpter;
    private List<SonicWave.SonicWaveData> sonicWaveData;

    public SonicWaveView(Context context)
    {
        super(context);
        initList(context);
    }

    public SonicWaveView(Context context, @Nullable AttributeSet attrs)
    {
        super(context, attrs);
        initList(context);
    }
    public SonicWaveView(Context context, @Nullable AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        initList(context);
    }


    public void setSonicWaveData(List<SonicWave.SonicWaveData> sonicWaveData,boolean isValid)
    {
        this.sonicWaveData.clear();
        for (int i = 0; i < sonicWaveData.size(); i++)
        {
            if (isValid)
            {
                if (sonicWaveData.get(i).isValid==0)
                {
                    this.sonicWaveData.add(sonicWaveData.get(i));
                }
            }
            else
            {
                if (sonicWaveData.get(i).isValid==1)
                {
                    this.sonicWaveData.add(sonicWaveData.get(i));
                }
            }
        }
        sonicWaveAdpter.notifyDataSetChanged();
    }


    public void setSonicWaveData(List<SonicWave.SonicWaveData> sonicWaveData)
    {
        this.sonicWaveData.clear();
        this.sonicWaveData.addAll(sonicWaveData);
        sonicWaveAdpter.notifyDataSetChanged();
    }


    private void initList(Context context)
    {
        LayoutManager layoutManager = new LinearLayoutManager(context);
        setLayoutManager(layoutManager);
        sonicWaveData = new ArrayList<>();
        sonicWaveAdpter = new SonicWaveAdpter(context,sonicWaveData);
        setAdapter(sonicWaveAdpter);
    }

    /**
     * 设置编辑状态是否打开
     *
     * */
    public void setPattern(byte currenPattern)
    {
        current_pattern = currenPattern;
        sonicWaveAdpter.notifyDataSetChanged();
    }
    public byte getCurrentPattern()
    {
        return current_pattern;
    }
    public void setOnItemValidChangedListener(OnItemValidChangedListener onItemValidChangedListener)
    {
        this.onItemValidChangedListener = onItemValidChangedListener;
    }

    public interface OnItemValidChangedListener {
        void onChanged(String uuid, boolean isValid);
    }


    private class SonicWaveAdpter extends RecyclerView.Adapter<WaveViewHodler>
    {
        private Context context;
        private List<SonicWave.SonicWaveData> sonicWaveDatas;

        private SonicWaveAdpter(Context context, List<SonicWave.SonicWaveData> sonicWaveDatas)
        {
            this.context = context;
            this.sonicWaveDatas = sonicWaveDatas;
        }

        @Override
        public WaveViewHodler onCreateViewHolder(ViewGroup viewGroup, int i)
        {
            View bootView = LayoutInflater.from(context).inflate(R.layout.wave_view_item_layout,viewGroup,false);
            return new WaveViewHodler(bootView);
        }

        @Override
        public void onBindViewHolder(WaveViewHodler waveViewHodler, final int i)
        {
            waveViewHodler.mWaveView.setWaveData(sonicWaveData.get(i), (i % 2 == 1),i);
            switch (current_pattern)
            {
                case PATTERN_EDIT:
                    waveViewHodler.mActionValid.setVisibility(VISIBLE);
                    if (sonicWaveData.get(i).isValid==1)
                    {
                        waveViewHodler.mActionValid.setImageDrawable(ContextCompat.getDrawable(context,R.mipmap.low_strain_db_view_add));
                    }
                    else
                    {
                        waveViewHodler.mActionValid.setImageDrawable(ContextCompat.getDrawable(context,R.mipmap.low_strain_db_view_remove));
                    }
                    waveViewHodler.mActionValid.setOnClickListener(new OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            if (onItemValidChangedListener!=null)
                            {
                                boolean changeValidState = sonicWaveData.get(i).isValid==1;
                                onItemValidChangedListener.onChanged(sonicWaveData.get(i).uuid,changeValidState);
                                //移除有效数据
                                sonicWaveData.remove(i);
                                notifyDataSetChanged();
                            }
                        }
                    });
                    break;
                case PATTERN_NORMAL:
                    waveViewHodler.mActionValid.setVisibility(GONE);
                    break;
            }
        }


        @Override
        public int getItemCount()
        {
            return sonicWaveDatas.size();
        }
    }

    private class WaveViewHodler extends RecyclerView.ViewHolder
    {
        private WaveView mWaveView;
        private LinearLayout Item_Layout;
        private ImageView mActionValid;
        public WaveViewHodler(View itemView)
        {
            super(itemView);
            mActionValid = (ImageView) itemView.findViewById(R.id.Valid_Action);
            Item_Layout = (LinearLayout) itemView.findViewById(R.id.Item_Layout);
            mWaveView = new WaveView(getContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 120);
            params.gravity = Gravity.CENTER_VERTICAL;
            mWaveView.setLayoutParams(params);
            Item_Layout.addView(mWaveView);
        }
    }
    public static class WaveView extends View
    {
        private int height;
        private int width;
        private Paint paint;
        private float delta_x;
        private float delta_y;
        private Path path;
        ArrayList<Integer> waveData;
        public WaveView(Context context)
        {
            super(context);
            init();
        }

        public WaveView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            init();
        }

        public WaveView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init();
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            height = getMeasuredHeight();
            width = getMeasuredWidth();
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom)
        {
            super.onLayout(changed, left, top, right, bottom);
        }

        @Override
        protected void onDraw(Canvas canvas)
        {
            super.onDraw(canvas);
            path.reset();
            if (sonicWaveData==null)
            {
                paint.setColor(Color.RED);
                paint.setTextAlign(Paint.Align.CENTER);
                paint.setTextSize(UiUtils.dip2px(20f));
                canvas.drawText("没有数据",width/2,height/2,paint);
                return;
            }
            //绘制深度
            paint.setColor(Color.WHITE);
            paint.setStyle(Paint.Style.FILL);
            paint.setStrokeWidth(4);
            paint.setTextSize(UiUtils.sp2px(14));
            String depth = String.format("%.2fm",sonicWaveData.depth/(float)1000);
            Paint.FontMetrics fontMetrics =  paint.getFontMetrics();
            canvas.drawText(depth,5,height/2+Math.abs(fontMetrics.ascent),paint);

            //绘制曲线
            //paint.setColor(ContextCompat.getColor(context,R.color.colorPrimary));
            paint.setStyle(Paint.Style.STROKE);
            if (ischangeColor)
                paint.setColor(Color.GREEN);
            else
                paint.setColor(Color.RED);
            float maxValue = getCollMax(sonicWaveData.waveData);
            if (maxValue==0)
            {
                delta_y = 1;
            }
            else
            {
                delta_y = (float) height/(2*maxValue);
            }
            int sampleLentht = sonicWaveData.waveData.length;
            delta_x = (float) width/sampleLentht;
            path.moveTo(0,height/2);
            canvas.drawPath(path,paint);
            for (int i = 0; i < sampleLentht; i++)
            {
                path.lineTo(i*delta_x,height/2+sonicWaveData.waveData[i]*delta_y);
            }
            canvas.drawPath(path,paint);

            //绘制首波位置
            paint.setColor(Color.YELLOW);
            paint.setStrokeWidth(6);
            canvas.drawLine(sonicWaveData.T1*delta_x,height/2-30,sonicWaveData.T1*delta_x,height/2+30,paint);

        }

        private void init()
        {
            paint = new Paint();
            paint.setAntiAlias(true);
            path = new Path();
            waveData = new ArrayList<>();
        }

        private boolean ischangeColor = false;
        private int index;
        private SonicWave.SonicWaveData sonicWaveData;
        private void setWaveData(SonicWave.SonicWaveData sonicWaveData,boolean ischangeColor,int index)
        {
            this.index = index;
            this.ischangeColor = ischangeColor;
            this.sonicWaveData = sonicWaveData;
            invalidate();
        }

        private float getCollMax(Integer[] wavedata)
        {
            waveData.clear();
            waveData.addAll(Arrays.asList(wavedata));
            int sampleLentht = wavedata.length;
            delta_x = (float) width/sampleLentht;
            return Collections.max(waveData, new Comparator<Integer>()
            {
                @Override
                public int compare(Integer o1, Integer o2)
                {
                    return Math.abs(o1)-Math.abs(o2);
                }
            });
        }
    }
}
